import {AfterViewInit, Component, OnInit} from '@angular/core';
import {NzTreeFlatDataSource, NzTreeFlattener} from "ng-zorro-antd/tree-view";
import {FavoriteGroup} from "@shared/models/UserInfo";
import {FlatTreeControl} from '@angular/cdk/tree';
import {NzContextMenuService, NzDropdownMenuComponent} from "ng-zorro-antd/dropdown";
import {NzModalService} from "ng-zorro-antd/modal";
import {InputDialogContent} from "@/app/pages/common/input-dialog-content";
import {FavoriteActionReq, UserActionService, UserGroupActionReq} from "@core/service/UserActionService";
import {BBYUtils} from "@shared/utils/BBYUtils";
import {NzMessageService} from "ng-zorro-antd/message";
import {AuthService} from "@core/service/AuthService";

interface FlatNode {
  expandable: boolean;
  id: string
  name: string
  level: number
  disabled: boolean
  createTime: string
}

interface FavoriteNode {
  name: string
  disabled?: boolean
  content?: FavoriteNode[]
  id?: string
  fileId?: string
  createTime?: string
}

@Component({
  selector: 'app-favorite',
  templateUrl: './favorite.component.html',
  styleUrls: ['./favorite.component.scss']
})
export class FavoriteComponent {
  TREE_DATA: FavoriteGroup[] = [
    {
      id: 'idididididi1111',
      name: '默认分组',
      content: [
        {
          fileId: 'fileIdfileIdfileIdfileId111',
          name: '文件1',
          createTime: new Date().toDateString()
        },
        {
          fileId: 'fileIdfileIdfileIdfileId222',
          name: '文件2',
          createTime: new Date().toDateString()
        }
      ]
    },
    {
      id: 'idididididi2222',
      name: '自定义分组',
      content: [
        {
          fileId: 'fileIdfileIdfileIdfileId111',
          name: '自定义文件1',
          createTime: new Date().toDateString()
        },
        {
          fileId: 'fileIdfileIdfileIdfileId222',
          name: '自定义文件2',
          createTime: new Date().toDateString()
        }
      ]
    }
  ];
  private transformer = (node: FavoriteNode, level: number): FlatNode => ({
    expandable: !!node.content,
    name: node.name,
    level,
    disabled: !!node.disabled,
    id: node.id || node.fileId || '',
    createTime: node.createTime||''
  });

  treeControl = new FlatTreeControl<FlatNode>(
    node => node.level,
    node => node.expandable
  );

  treeFlattener = new NzTreeFlattener(
    this.transformer,
    node => node.level,
    node => node.expandable,
    node => node.content
  );

  dataSource = new NzTreeFlatDataSource(this.treeControl, this.treeFlattener);
  // 右键菜单操作对象
  selectedNode: FlatNode | undefined

  loading=false
  idParentMap=new Map<string,string>()
  constructor(
    private dialogService: NzModalService,
    private nzContextMenuService: NzContextMenuService,
    private userActionService:UserActionService,
    private message: NzMessageService
  ) {
    this.dataSource.setData(this.TREE_DATA);
    this.flash()
  }
  setData(data:FavoriteGroup[]){
    this.idParentMap.clear();
    for (let group of data){
      if (group.content&&group.content.length>0){
        for(let file of group.content){
          this.idParentMap.set(group.id,file.fileId)
        }
      }
    }
    this.dataSource.setData(data)
  }
  flash() {
    this.loading=true;
    BBYUtils.handelResult(
      this.userActionService.getFavorites(),
      res => {
        console.log(res)
        this.dataSource.setData(res.data)
        AuthService.saveFavorites(res.data)
        this.loading=false;
      },
      res => {
        this.loading=false;
        this.message.error(res.msg)
      });
  }
  hasChild = (_: number, node: FlatNode): boolean => node.expandable;

  getNode(name: string): FlatNode | null {
    return this.treeControl.dataNodes.find(n => n.name === name) || null;
  }

  test() {
    console.log('====')
  }

  openClick(){
    if (!this.selectedNode){
      return
    }
    if (this.selectedNode.expandable){
      this.treeControl.expand(this.selectedNode)
    }
  }
  rightClickFile($event: MouseEvent, rightClickMenu: NzDropdownMenuComponent, node: FlatNode) {
    this.selectedNode=node;
    console.log(node)
    this.nzContextMenuService.create($event, rightClickMenu);
  }

  deleteClick() {
    if (!this.selectedNode){
      return
    }
    let node = this.selectedNode;
    this.dialogService.warning({
      nzTitle: '删除',
      nzWidth: '400px', nzCentered: true,
      nzCancelText:'取消',
      nzContent: node.expandable?`收藏 [${node.name}] 是一个分组，继续将删除此分组下所有收藏记录，是否确认删除？`:`确认要删除收藏：[${node.name}] ？`,
      nzOnOk: ($event: Event) =>
        new Promise((resolve) => {
          let data:FavoriteActionReq;
          if (node.expandable){
            data = {
              opera:'deleteGroup',
              groupId:node.id,
            }
          }else {
            data = {
              opera:'deleteFav',
              groupId:this.idParentMap.get(node.id),
              fileId:node.id,
            }
          }
          this.setFavorites(data,resolve)
        })
    })
  }

  renameClick() {
    if (!this.selectedNode){
      return
    }
    let node = this.selectedNode;
    this.dialogService.create({
      nzTitle: '重命名',nzWidth:'400px',
      nzContent: InputDialogContent,
      nzComponentParams:{
        value:node.name
      },
      nzOnOk: (page) =>
        new Promise((resolve) => {
        let data:FavoriteActionReq;
        if (node.expandable){
          data = {
            opera:'renameGroup',
            groupId:node.id,
            newName:page.value
          }
        }else {
          data = {
            opera:'renameFav',
            groupId:this.idParentMap.get(node.id),
            fileId:node.id,
            newName:page.value
          }
        }
        this.setFavorites(data,resolve)
      })
    })
  }
  addGroupClick() {
    this.dialogService.create({
      nzTitle: '新建收藏夹', nzWidth: '400px',
      nzContent: InputDialogContent,
      nzComponentParams: {
        placeholder:'请输入收藏夹名'
      },
      nzOnOk: (page) =>
        new Promise((resolve) => {
        let data:FavoriteActionReq = {
          opera:'addGroup',
          newName:page.value
        }
        this.setFavorites(data,resolve)
      })
    })
  }
  setFavorites(data:FavoriteActionReq,resolve:any) {
    BBYUtils.handelResult(
      this.userActionService.setFavorites(data),
      res => {
        this.dataSource.setData(res.data)
        AuthService.saveFavorites(res.data)
        resolve()
      },
      res => {
        this.message.error(res.msg)
        resolve()
      }
    )
  }

}
